/**
 * @文件名称: TermQuartz.java
 * @版权声明 : Copyright (C) 2008-2016 北斗天汇（北京）科技有限公司
 * @创建人员: 徐斌
 * @文件描述:
 * @修改时间: 2017年6月16日 上午8:58:04
 * @修改历史： 2017年6月16日
 */

package com.bdth.controller;

import com.bdth.model.Device;
import com.bdth.model.PageModel;
import com.bdth.model.User;
import com.bdth.service.IDeviceBindService;
import com.bdth.service.IDeviceService;
import com.bdth.utils.DateUtil;
import com.bdth.utils.HtmlUtil;
import com.bdth.utils.SessionUtils;
import com.bdth.utils.StringUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Controller
@RequestMapping("/device")
public class DeviceController extends BaseController {

	@Autowired
	private IDeviceService deviceService;

	@Autowired
	private IDeviceBindService deviceBindService;

	@Autowired
	private RedisTemplate redisTemplate;

	/**
	 * 首页
	 *
	 * @return
	 */
	@RequestMapping("/list")
	public ModelAndView list(HttpServletRequest request)
			throws Exception {
		return forword("/device/deviceList");
	}

	/**
	 * json 列表页面
	 *
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/dataList")
	public void dataList(PageModel pageModel, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		String equipName = request.getParameter("equipName");
		String simNo = request.getParameter("simNo");
		String depIdSearch = "" + request.getParameter("depIdSearch");
		String typeID = request.getParameter("typeID");
		map.put("equipName", equipName);
		map.put("simNo", simNo);
		map.put("typeID", typeID);
		User user = SessionUtils.getUser(request);
		if (!StringUtil.isEmptyWithNullStr(depIdSearch) && !"0".equals(depIdSearch)) {
			List<Integer> depIds = getDepIds(Integer.valueOf(depIdSearch));
			map.put("depIds", depIds);
		} else {
			List<Integer> depIds = getDepIds(user.getDepId());
			map.put("depIds", depIds);
		}


		//紧跟着的第一个查询方法会被分页
		PageHelper.startPage(pageModel.getPage(), pageModel.getRows());
		List<Map> dataList = deviceService.queryMapDataByMapList(map);
		//获得结果集条总数
		PageInfo pageList = new PageInfo(dataList);
		//设置页面数据
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		jsonMap.put("total", pageList.getTotal());
		jsonMap.put("rows", dataList);
		HtmlUtil.writerJson(response, jsonMap);
	}


	@RequestMapping("/getId")
	public void getId(Integer id, HttpServletResponse response)
			throws Exception {
		Map<String, Object> context = getRootMap();
		Device bean = deviceService.queryById(id);
		if (bean == null) {
			sendFailureMessage(response, "没有找到对应的记录!");
			return;
		}
		context.put(SUCCESS, true);
		context.put("data", bean);
		HtmlUtil.writerJson(response, context);
	}


	/**
	 * 添加或修改数据
	 *
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/save")
	public void save(Device bean, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		Map<String, Object> context = new HashMap<String, Object>();

		if (StringUtil.isEmptyWithNullStr(bean.getSimNo())) {
			sendFailureMessage(response, "请输入设备号!");
			return;
		}

		Device device = deviceService.queryBySimNo(bean.getSimNo().trim());
		Device device1 = deviceService.queryByEquipName(bean.getEquipName().trim());
		String startTime = "" + request.getParameter("startTimeHidden");
		String endTime = "" + request.getParameter("endTimeHidden");
		String lastCheckTime = "" + request.getParameter("lastCheckTimeHidden");
		bean.setStartTime(DateUtil.getDateFromString(startTime));
		bean.setEndTime(DateUtil.getDateFromString(endTime));
		bean.setLastCheckTime(DateUtil.getDateFromString(lastCheckTime));
		bean.setSimNo(bean.getSimNo().trim());
		if (bean.getDepId().intValue() == 0 || StringUtil.isEmptyWithNullStr(bean.getDepName())) {
			sendFailureMessage(response, "请选择所属分组!");
			return;
		}
		if (bean.getId() == null) {
			bean.setCreateDate(new Date());
			if (device1 != null) {
				sendFailureMessage(response, "显示名称已存在.");
				return;
			}
			if (device != null) {
				sendFailureMessage(response, "设备号已存在.");
				return;
			}
			deviceService.add(bean);
			//redis添加限速
			ValueOperations<String, String> stringOperations = redisTemplate
					.opsForValue();
			stringOperations.set("speedLimit_" + bean.getSimNo().trim(), "" + bean.getSpeedLimit());
		} else {

			if (device1 != null && device1.getId().intValue() != bean.getId().intValue()) {
				sendFailureMessage(response, "显示名称已存在.");
				return;
			}
			if (device != null && device.getId().intValue() != bean.getId().intValue()) {
				sendFailureMessage(response, "设备号已存在.");
				return;
			}
			if (!Device.CommunicationModel_GPRS_RDSS.equals(bean.getCommunicationModel())) {
				bean.setSimIOT("");
			}
			deviceService.updateBySelective(bean);
			//redis添加限速
			ValueOperations<String, String> stringOperations = redisTemplate
					.opsForValue();
			stringOperations.set("speedLimit_" + bean.getSimNo().trim(), "" + bean.getSpeedLimit());
		}
		sendSuccessMessage(response, "保存成功~");
	}


	@RequestMapping("/delete")
	public void delete(Integer[] id, HttpServletResponse response)
			throws Exception {
		deviceService.delete(id);
		sendSuccessMessage(response, "删除成功");
	}

	/**
	 * 假删除
	 *
	 * @param id
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/fakeDelete")
	public void fakeDelete(Integer[] id, HttpServletResponse response)
			throws Exception {

		for (int i : id) {

			Device bean = deviceService.queryById(i);
			if (bean != null) {
				if (bean.getTypeID() == 0) {
					Map<String, Object> map = new HashMap<String, Object>();
					List parentSimList = new ArrayList<>();
					parentSimList.add(bean.getSimNo());
					map.put("parentSims", parentSimList);
					List<Map> dataList = deviceBindService.queryBindDataByMapList(map);
					if (dataList != null && dataList.size() > 0) {
						sendFailureMessage(response, "该卡下分配有子卡，不能删除!");
						break;
					}
				} else {
					Map<String, Object> map1 = new HashMap<String, Object>();
					map1.put("simNo", bean.getSimNo());
					List<Map> dataList1 = deviceBindService.queryBindDataByMapList(map1);
					if (dataList1 != null && dataList1.size() > 0) {
						sendFailureMessage(response, "该卡已被绑定使用，请先解绑，再删除!");
						break;
					}
				}

			}

			Device device = new Device();
			device.setId(i);
			device.setDeleted(1);
			deviceService.deleteFake(device);
			sendSuccessMessage(response, "删除成功");
		}

	}


	@RequestMapping("/reloadSpeed")
	public void reloadSpeed(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		List<Device> dataList = deviceService.queryByMapList(map);
		for (Device bean : dataList) {

			if (!StringUtil.isEmptyWithNullStr("" + bean.getSpeedLimit())) {
				//redis添加限速
				ValueOperations<String, String> stringOperations = redisTemplate
						.opsForValue();
				stringOperations.set("speedLimit_" + bean.getSimNo().trim(), "" + bean.getSpeedLimit());
			}
		}

		sendSuccessMessage(response, "同步成功");
	}

}
